package com.lib.framework.helper.permission

import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import com.lib.framework.manager.LogManager

/**
 * Copyright (C), 2020-2020, 享物说
 * FileName: PermissionFragment
 * Author: keanbin
 * Date: 2020-02-05 10:29
 * Description: 辅助处理权限申请结果的 fragment
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class PermissionFragment : Fragment() {

    companion object {
        private const val PERMISSIONS_REQUEST_CODE = 42
        private const val TAG = "PermissionFragment"
    }

    /**
     * 权限申请回调
     */
    private var mPermissionsCallback: PermissionsCallback? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.retainInstance = true
    }

    /**
     * 申请权限
     */
    @TargetApi(23) fun requestPermissions(@NonNull permissions: Array<String>, permissionsCallback: PermissionsCallback) {
        mPermissionsCallback = permissionsCallback
        this.requestPermissions(permissions, PERMISSIONS_REQUEST_CODE)
    }

    /**
     * 权限申请结果
     */
    @TargetApi(23) override fun onRequestPermissionsResult(requestCode: Int,
                                                           permissions: Array<out String>,
                                                           grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            val permissionResultList = mutableListOf<PermissionResult>()
            for (i in permissions.indices) {
                val granted = grantResults[i] == 0
                val shouldShowRequestPermissionRationale = this.shouldShowRequestPermissionRationale(permissions[i])
                val permission = PermissionResult(permissions[i], granted, shouldShowRequestPermissionRationale)
                LogManager.i(TAG, "onRequestPermissionsResult  $permission")

                permissionResultList.add(permission)
            }
            mPermissionsCallback?.onResult(permissionResultList)
        }
    }

    /**
     * 权限是否已授权
     */
    @TargetApi(23) fun isGranted(permission: String): Boolean {
        val fragmentActivity = this.activity
        return if (fragmentActivity == null) {
            throw IllegalStateException("This fragment must be attached to an activity.")
        } else {
            fragmentActivity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
        }
    }

    /**
     * 权限是否撤销
     */
    @TargetApi(23) fun isRevoked(permission: String): Boolean {
        val fragmentActivity = this.activity
        return fragmentActivity?.packageManager?.isPermissionRevokedByPolicy(permission, fragmentActivity.packageName)
            ?: throw IllegalStateException("This fragment must be attached to an activity.")
    }

    /**
     * 权限申请回调
     */
    interface PermissionsCallback {

        /**
         * 权限申请结果
         */
        fun onResult(permissionResultList: List<PermissionResult>)
    }
}